package com.lib.framework.widget.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView

/**
 * Copyright (C), 2020-2020, 享物说
 * FileName: BaseBindingAdapter
 * Author: keanbin
 * Date: 2020-02-09 17:48
 * Description: 基本使用的 databinding 的adatper
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
abstract class BaseBindingAdapter<M, B: ViewDataBinding>(
    val context: Context,
    val data: MutableList<M> = mutableListOf()
): RecyclerView.Adapter<BaseBindingAdapter.BaseBindingViewHolder>() {

    fun getItems(): MutableList<M> {
        return data
    }

    override fun getItemCount(): Int {
        return data.size
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseBindingViewHolder {
        val binding = DataBindingUtil.inflate<ViewDataBinding>(LayoutInflater.from(context), getLayoutResId(viewType), parent, false)
        return BaseBindingViewHolder(binding.root)
    }

    override fun onBindViewHolder(holder: BaseBindingViewHolder, position: Int) {
        val binding = DataBindingUtil.getBinding<B>(holder.itemView)
        this.onBindItem(binding, data[position], position)
    }

    @LayoutRes
    protected abstract fun getLayoutResId(viewType: Int): Int

    protected abstract fun onBindItem(binding: B?, item: M, position: Int)

    class BaseBindingViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}